package com.tidc.authorization.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tidc.authorization.mapper.UserMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;

/**
 * @ClassNmae MyUserDeatisService
 * @Description TODO
 * @Author 14631
 **/
@Component
@CrossOrigin //解决跨域问题
public class MyUserDeatisService implements UserDetailsService{
	@Autowired
	private UserMapper userMapper;
	@Autowired
	ClientDetailsService clientDetailsService;
	@Override
	public UserDetails loadUserByUsername(String email) {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		//没有认证统一采用httpbasic认证，httpbasic中存储了client_id和client_secret，开始认证client_id和client_secret
		if(authentication==null){
			ClientDetails clientDetails = clientDetailsService.loadClientByClientId(email);
			if(clientDetails!=null){
				//密码
				String clientSecret = clientDetails.getClientSecret();
				return new User(email,clientSecret,AuthorityUtils.commaSeparatedStringToAuthorityList(""));
			}
		}
		System.out.println(email+"登录");
		QueryWrapper<com.tidc.authorization.pojo.User> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("email",email);
		com.tidc.authorization.pojo.User user = userMapper.selectOne(queryWrapper);
		if (user!=null) {
			return new User(user.getEmail(),user.getPassword(),AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER,ROLE_ADMIN"));

		}
		return new User("1463158635@qq.com","123",AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER,ROLE_ADMIN"));
	}


}
